package UIFree.effects
{
	import UIFree.ObjectEvent;
	import UIFree.uif_ecomponent;
	
	import UIUtils.uif_util;
	
	import flash.events.Event;
	import flash.geom.Rectangle;

	public class uif_effect extends uif_ecomponent {
		private var _options	: Object;
		private var _frame		: int;
		
		public static const STARTEFFECT			: String = 'STARTEFFECT';
		public static const REQUIRESTOPEFFECT	: String = 'REQUIRESTOPEFFECT';
		public static const STOPEFFECT			: String = 'STOPEFFECT';
		public static const UPDATE				: String = 'UPDATE';
		
		public function uif_effect(parent: uif_ecomponent, styleClass: Object=null) {
			var inner: Rectangle = parent.getInner();
			super(parent, inner.x, inner.y, inner.width, inner.height, styleClass);
		}
		
		public function start(a_options: Object): void {
			_options = uif_util.union(defaultOptions(), a_options);
			doStart();
		}
		
		public function stop(): void {
			_options = null;
			doStop();
		}
		
		public function requireStop(): void {
			dispatchEvent(new Event(REQUIRESTOPEFFECT));
			stop();
		}
		
		public function get options(): Object {
			return _options;
		}
		
		public function get live(): int {
			return _options.hasOwnProperty('live')?_options.live:0;
		}
		
		public function checkLive(a_frame: int): Boolean {
			return ((live > 0) && (_frame < live)) || (live == 0);
		} 
		
		protected function doFrame(e: Event): void {
			if (_options != null) {
				_frame++;
				if (!checkLive(_frame)) requireStop();
				if (_options) update(_frame);
			}
		}
		
		public function get frame(): int {
			return _frame;
		}
// Методы переопределения
		
		protected function defaultOptions(): Object {
			return {
				This		: This
			};
		}
		
		protected function doStart(): void {
			_frame	 = 0;
			addEvent(Event.ENTER_FRAME, doFrame);
			dispatchEvent(new Event(STARTEFFECT));
		}
		
		protected function doStop(): void {
			removeEventListener(Event.ENTER_FRAME, doFrame);
			dispatchEvent(new Event(STOPEFFECT));
		} 
		
		protected function update(a_frame: int): void {
			dispatchEvent(new ObjectEvent(UPDATE, this));
		}
	}
}